/*  处理oss地址生成带水印的url  */
import { getlocalinfo } from '@/utils/utils.js';
import store from '../store';
const base64 = require('@/utils/base64.js');

function urlSafeBase64Encode(str = '') {
	// 限制文本不能超过64字节
	const maxBytes = 60;
	let byteCount = 0;
	for (let i = 0; i < str.length; i++) {
		const charCode = str.charCodeAt(i);
		byteCount += charCode > 0x7FF ? 3 : charCode > 0x7F ? 2 : 1;
		if (byteCount > maxBytes) {
			str = str.slice(0, i) + '...';
			break;
		}
	}
	return base64.encode(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function getImginfo(data) {
	return new Promise((resolve) => {
		uni.getImageInfo({
			// 可以是本地路径或网络图片地址
			src: data,
			success: function (res) { 
				resolve(res);
			},
			fail: function (err) {
				console.log('获取图片信息失败', err);
				resolve({});
			}
		});
	});
}
// 获取经纬度信息
function getLocalInfo() {
	return new Promise((resolve) => {
		if (getApp().globalData.localinfo.latitude) {
			if (
				new Date().getTime() - getApp().globalData.localinfo.time <=
				1000 * 60 * 1
			) {
				resolve(getApp().globalData.localinfo);
				return;
			}
		}

		uni.getLocation({
			type: 'gcj02',
			success(res) { 
				getApp().globalData.localinfo = {
					...res,
					time: new Date().getTime(),
				};
				resolve(res);
			},
			fail(err) {
				console.log('位置信息获取失败', err);
				resolve({});
			},
		});
	});
}

// 获取水印数据（所有相册选图片用
export async function getWaterMarkInfo() {
	let localInfo = {};
	let addressText = '无法获取定位地址';
	let buildingName = '';
	let elevatorName = ''; 
	if (store.state.system.onlineStatus) {
		localInfo = await getLocalInfo();
		try {
			if (localInfo.latitude) {
				let address = await getlocalinfo(localInfo.latitude, localInfo.longitude);
				if (address.result) {
					addressText = address.result.formatted_addresses ? address.result.formatted_addresses.recommend : address.result.address;
				}
			}
		} catch (error) {
			console.log('获取定位失败', error);
		}
	}
	try {
		// 从当前页面取
		let pages = getCurrentPages();
		let pag = pages[pages.length - 1]; 
		if (pag.route && pag.route.indexOf('workOrders/detail') != -1) {
			// 保养详情页 

			// #ifndef H5	
			buildingName = pag.data.eleInfo.buildingName;
			elevatorName = pag.data.eleInfo.elevatorAddress;
			// #endif

			// #ifdef H5
			buildingName = pag.$data.eleInfo?.buildingName || '';
			elevatorName = pag.$data.eleInfo?.elevatorAddress || '';
			// #endif
		}
	} catch (error) {
		console.log(error);
	}

	let date = new Date();
	const year = date.getFullYear();
	const month = date.getMonth() + 1;
	const day = date.getDate();
	const hour = date.getHours();
	const minute = date.getMinutes();
	const second = date.getSeconds();
	let watermarkInfo = {
		createTime: `${year}-${month > 9 ? month : '0' + month}-${day > 9 ? day : '0' + day} ${hour > 9 ? hour : '0' + hour}:${minute > 9 ? minute : '0' + minute}:${second > 9 ? second : '0' + second}`,
		buildingName: buildingName,
		elevatorName: elevatorName,
		latitude: localInfo.latitude || '',
		longitude: localInfo.longitude || '',
		address: addressText || '',
	};
	return watermarkInfo;
}

// org 原图地址
export async function generateWatermarkedUrl({ org = '', url = '', watermarks = [], imgId = '' }) {
	let y = 30;
	let texts = [];
	let resize = '/resize,w_400';
	// 水印文字缩放倍率
	let rag = 1;
	const imginfo = await getImginfo(org);
	if (imginfo.width) {
		resize = '';
		rag = (imginfo.width / 400).toFixed(0);
	}
	y = y * rag;

	const idTxt = `/watermark,text_${urlSafeBase64Encode(imgId)},g_se,color_ffffff,size_${12 * rag},x_${10 * rag},y_${10 * rag}`;
	texts.push(idTxt);
	for (let i = watermarks.length - 1; i >= 0; i--) {
		const wm = watermarks[i];
		let size = Number(wm.fontSize || 12) * rag;
		const res = `/watermark,text_${urlSafeBase64Encode(wm.content)},g_${wm.align == 'right' ? 'se' : 'sw'},color_${wm.color || 'ffffff'},size_${(wm.fontSize || 12) * rag},x_${(wm.x || 10) * rag},y_${y}`;
		y = (wm.lineHeight || 8) * rag + size + y;
		 
		texts.push(res);
	}

	const watermarkParams = texts.join('');

	return `${url}?x-oss-process=image${resize}${watermarkParams}`;
}

function getUserInfo() {
	return new Promise((resolve) => {
		uni.getStorage({
			key: 'userData',
			success: (res) => {
				let userinfo = res.data || {};
				resolve(userinfo);
			}
		});
	});
}

export function setImageInfo(id, data) {
	return new Promise((resolve) => {
		uni.setStorage({
			key: id,
			data,
			success: () => {
				console.log(JSON.stringify(data), `Success: setImageInfo ${id}`);
				resolve();
			}
		});
	});
}

export function getImageInfo(id) {
	return new Promise((resolve) => {
		uni.getStorage({
			key: id,
			success: (res) => { 
				resolve(res.data);
			},
			fail: () => {
				resolve({});
			}
		});
	});
}

// 根据图片路径获取本地head信息
export async function getPathInfo(path) {
	return new Promise((resolve) => {
		uni.getStorage({
			key: 'imgPaths',
			success: (res) => {
				let paths = res.data || {};
				let imgId = '';
				for (const key in paths) {
					if (paths[key] == path) {
						imgId = key;
						break;
					}
				}
				if (imgId) {
					uni.getStorage({
						key: imgId,
						success: (res) => {
							resolve({ ...(res.data || {}), imgId });
						},
						fail: () => {
							resolve({});
						}
					});
				} else {
					resolve({});
				}
			},
			fail: () => {
				resolve({});
			}
		});
	});
}
// 新增本地路径与imgId的绑定关系
export function setPath(path, id) {
	uni.getStorage({
		key: 'imgPaths',
		success: (res) => {
			let paths = res.data || {};
			paths[id] = path;
			uni.setStorage({
				key: 'imgPaths',
				data: paths
			});
		},
		fail: () => {
			let paths = {};
			paths[id] = path;
			uni.setStorage({
				key: 'imgPaths',
				data: paths
			});
		}
	});
}

// 删除绑定关系
export function removePath(path) {
	let imgId = '';
	uni.getStorage({
		key: 'imgPaths',
		success: (res) => {
			let paths = res.data || {};

			for (const key in paths) {
				if (paths[key] == path) {
					imgId = key;
					delete paths[imgId];
					break;
				}
			}
			uni.setStorage({
				key: 'imgPaths',
				data: paths
			});
			if (imgId) {
				console.log('removeStorage', imgId);
				uni.removeStorage({
					key: imgId,
					fail: (err) => {
						console.log(err);
					}
				});
			}
		}
	});
}

// 缓存水印数据并同时生成图片id  
export async function setWatermarkJson(options) {
	console.log('setWatermarkJson',options);
	let randoms = (Math.random() * 10).toFixed(0);
	// 零时图片id
	const userinfo = await getUserInfo();
	const imgId = options.imgId || (userinfo.tenant_id || '') + String(new Date().getTime()) + '' + String(randoms);

	// 如果options.watermark.createTime 缺少秒 则补充 :00
	if (options.watermark && options.watermark.createTime) {
		let ct = options.watermark.createTime;
		// 检查时间格式是否为 "YYYY-MM-DD HH:mm"（缺少秒）
		if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/.test(ct)) {
			options.watermark.createTime = ct + ':00';
		}
	}

	const imgData = {
		width: '',
		height: '',
		'plan_id': options.plan_id || options.planId || '',
		'template_id':options.template_id ||  options.templateId || '',
		'template_name':  options.template_name || options.templateName || '',
		// 保养任务位置分类idmg-from
		'location_type_id': options.location_type_id || options.locationIds || '',
		// 保养任务位置分类名称
		'location_type_name':options.location_type_name || options.locationNames || '',
		// 工作项id
		'template_content_id': options.template_content_id || options.templateContentId || '',
		// 工作项名称
		'template_content_name':  options.template_content_name || options.templateContentName || '',
		// 入口（1-签到保养 2-保养签退 3-保养工作项内容
		'img_from':  options.img_from || options.type || '',
		// 识别结果（:1-正常 2-异常 3-无法识别
		result: options.result === undefined ? '' : options.result,
		// 水印数据（时间，项目，电梯，定位
		watermark: options.watermark || '',
		// 模型数据（框定位坐标，结果
		'model_result': options.model_result || '',
		// 模型id
		'model_id': options.model_id,
		// 租户id
		'tenant_id': userinfo.tenant_id,
		'create_user': userinfo.user_id,
		// 当前AI 业务结果
		'business_result': options.business_result || '',
		// 当前AI业务配置
		'ai_business_config': options.ai_business_config || '',
	}; 
	await setImageInfo(imgId, imgData);

	console.log('[setWatermarkJson] imgData', JSON.stringify(imgData));

	return imgId;
}